/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.easemob.chatuidemo.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactManager;
import com.easemob.chat.EMConversation;
import com.easemob.chatuidemo.Constant;
import com.easemob.chatuidemo.adapter.ContactAdapter;
import com.easemob.chatuidemo.db.InviteMessgeDao;
import com.easemob.chatuidemo.db.UserDao;
import com.easemob.chatuidemo.widget.Sidebar;
import com.easemob.exceptions.EaseMobException;

import net.mihome.app.AppContext;
import net.mihome.app.R;
import net.mihome.app.bean.User;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 联系人列表页
 * 
 */
public class ContactlistActivity extends BaseActivity {
    static ContactlistActivity instance;
	private ContactAdapter adapter;
	private List<User> contactList;
	private ListView listView;
	private boolean hidden;
	private Sidebar sidebar;
	private InputMethodManager inputMethodManager;
	private List<String> blackList;
    private View addNewFriendView;
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contact_list_activity);
		inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		listView = (ListView)findViewById(R.id.list);
		sidebar = (Sidebar) findViewById(R.id.sidebar);
		sidebar.setListView(listView);
        addNewFriendView=findViewById(R.id.iv_new_contact);
            addNewFriendView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //进入添加好友页面
                    startActivity(new Intent(ContactlistActivity.this, AddContactActivity.class));
                }
            });
		//黑名单列表
		blackList = EMContactManager.getInstance().getBlackListUsernames();
		contactList = new ArrayList<User>();
		// 获取设置contactlist
		getContactList();
		// 设置adapter
		adapter = new ContactAdapter(this, R.layout.row_contact, contactList, sidebar);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				String username = adapter.getItem(position).getUsername();
				if (Constant.NEW_FRIENDS_USERNAME.equals(username)) {
					// 进入申请与通知页面
					User user = AppContext.getInstance().getContactList().get(Constant.NEW_FRIENDS_USERNAME);
					user.setUnreadMsgCount(0);
					startActivity(new Intent(ContactlistActivity.this, NewFriendsMsgActivity.class));
				} else if (Constant.CONTACT_LIST_BLACK_LIST.equals(username)) {
					// 进入圈子列表页面
					startActivity(new Intent(ContactlistActivity.this, BlacklistActivity.class));
				}else if (Constant.ADD_CONTRACT.equals(username)) {
                    // 进入圈子列表页面
                    startActivity(new Intent(ContactlistActivity.this, AddContactActivity.class));
                }else {
					// demo中直接进入聊天页面，实际一般是进入用户详情页
                    User user=adapter.getItem(position);
                    Intent intent=new Intent(ContactlistActivity.this, ChatActivity.class).putExtra("userId",user.getOpenId());
                    intent.putExtra("userName",user.getName());
					startActivity(intent);
				}
			}
		});
		listView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// 隐藏软键盘
				if (ContactlistActivity.this.getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
					if (ContactlistActivity.this.getCurrentFocus() != null)
						inputMethodManager.hideSoftInputFromWindow(ContactlistActivity.this.getCurrentFocus().getWindowToken(),
								InputMethodManager.HIDE_NOT_ALWAYS);
				}
				return false;
			}
		});
		registerForContextMenu(listView);

	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		// 长按前两个不弹menu
		if (((AdapterContextMenuInfo) menuInfo).position > 2) {
            ContactlistActivity.this.getMenuInflater().inflate(R.menu.context_contact_list, menu);
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.delete_contact) {
			User tobeDeleteUser = adapter.getItem(((AdapterContextMenuInfo) item.getMenuInfo()).position);
			// 删除此联系人
			deleteContact(tobeDeleteUser);
			// 删除相关的邀请消息
			InviteMessgeDao dao = new InviteMessgeDao(this);
			dao.deleteMessage(tobeDeleteUser.getUsername());
			return true;
		}else if(item.getItemId() == R.id.add_to_blacklist){
			User user = adapter.getItem(((AdapterContextMenuInfo) item.getMenuInfo()).position);
			moveToBlacklist(user.getOpenId());
			return true;
		}
		return super.onContextItemSelected(item);
	}

	@Override
	public void onResume() {
		super.onResume();
		if (!hidden) {
			refresh();
		}
	}

	/**
	 * 删除联系人
	 * 
	 */
	public void deleteContact(final User tobeDeleteUser) {
		final ProgressDialog pd = new ProgressDialog(this);
		pd.setMessage("正在删除...");
		pd.setCanceledOnTouchOutside(false);
		pd.show();
		new Thread(new Runnable() {
			public void run() {
				try {
					EMContactManager.getInstance().deleteContact(tobeDeleteUser.getOpenId());
					// 删除db和内存中此用户的数据
					UserDao dao = new UserDao(ContactlistActivity.this);
					dao.deleteContact(tobeDeleteUser.getOpenId());
					AppContext.getInstance().getContactList().remove(tobeDeleteUser.getOpenId());
                    ContactlistActivity.this.runOnUiThread(new Runnable() {
                        public void run() {
                            pd.dismiss();
                            adapter.remove(tobeDeleteUser);
                            adapter.notifyDataSetChanged();

                        }
                    });
				} catch (final Exception e) {
                    ContactlistActivity.this.runOnUiThread(new Runnable() {
                        public void run() {
                            pd.dismiss();
                            Toast.makeText(ContactlistActivity.this, "删除失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });

				}

			}
		}).start();

	}

	/**
	 * 把user移入到黑名单
	 */
	private void moveToBlacklist(final String username){
		final ProgressDialog pd = new ProgressDialog(ContactlistActivity.this);
		pd.setMessage("正在移入黑名单...");
		pd.setCanceledOnTouchOutside(false);
		pd.show();
		new Thread(new Runnable() {
			public void run() {
				try {
					//加入到黑名单
					EMContactManager.getInstance().addUserToBlackList(username,false);
                    ContactlistActivity.this.runOnUiThread(new Runnable() {
                        public void run() {
                            pd.dismiss();
                            Toast.makeText(ContactlistActivity.this, "移入黑名单成功", Toast.LENGTH_SHORT).show();
                            refresh();
                        }
                    });
				} catch (EaseMobException e) {
					e.printStackTrace();
                    ContactlistActivity.this.runOnUiThread(new Runnable() {
                        public void run() {
                            pd.dismiss();
                            Toast.makeText(ContactlistActivity.this, "移入黑名单失败", Toast.LENGTH_SHORT).show();
                        }
                    });
				}
			}
		}).start();
		
	}
	
	// 刷新ui
	public void refresh() {
		try {
			// 可能会在子线程中调到这方法
			this.runOnUiThread(new Runnable() {
                public void run() {
                    getContactList();
                    adapter.notifyDataSetChanged();

                }
            });
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取联系人列表，并过滤掉黑名单和物业管家，且进行排序
	 */
	private void getContactList() {
		//获取本地好友列表
		Map<String, User> users = AppContext.getInstance().getContactList();
        if(users==null){
            return ;
        }
        contactList.clear();
		Iterator<Entry<String, User>> iterator = users.entrySet().iterator();
        User wuyeguanjiaUser=null;
		while (iterator.hasNext()) {
			Entry<String, User> entry = iterator.next();
			if (entry!=null&&!entry.getKey().equals(Constant.NEW_FRIENDS_USERNAME) && !entry.getKey().equals(Constant.CONTACT_LIST_BLACK_LIST)&& !entry.getKey().equals(Constant.ADD_CONTRACT)&& !blackList.contains(entry.getKey()))
            {
                User user=entry.getValue();
                EMConversation conversation = EMChatManager.getInstance().getConversation(user.getOpenId());
                user.setUnreadMsgCount(conversation.getUnreadMsgCount());
                if(user!=null&&user.getRealName()!=null&&user.getRealName().contains("物业管家")){
                    wuyeguanjiaUser=user;
                    continue;
                }
                contactList.add(entry.getValue());
            }
		}
		// 排序
		Collections.sort(contactList, new Comparator<User>() {

			@Override
			public int compare(User lhs, User rhs) {
				return lhs.getUsername().compareTo(rhs.getUsername());
			}
		});
//
//        //
//		// 加入"申请与通知"和"圈子"
//        users.get(Constant.CONTACT_LIST_BLACK_LIST);
		contactList.add(0, users.get(Constant.CONTACT_LIST_BLACK_LIST));
        wuyeguanjiaUser.setHeader("");
        contactList.add(1, wuyeguanjiaUser);
//		// 把"申请与通知"添加到首位
//		contactList.add(0, users.get(Constant.NEW_FRIENDS_USERNAME));
	}

}
